from collections import defaultdict
from typing import List
class Solution:
    def findXSum(self, nums: List[int], k: int, x: int) -> List[int]:
        n = len(nums)
        cnt = defaultdict(int)
        ans = []
        for i in range(n):
            if i < k-1:
                cnt[nums[i]] += 1
                continue
            cnt[nums[i]] += 1
            window = nums[i-k+1:i+1]
            # print("window:",window)
            # sorted_window = sorted(window,key=lambda x: (cnt[x],x),reverse=True)
            sorted_cnt = sorted(cnt.items(),key=lambda x: (x[1],x[0]),reverse=True)
            # print("sorted_window:",sorted_window)
            if len(cnt)<x:
                ans.append(sum(window))
            else:
                ans.append(sum(key*value for key, value in sorted_cnt[:x]))
            cnt[nums[i-k+1]] -= 1
            if cnt[nums[i-k+1]] == 0:
                del cnt[nums[i-k+1]]
        return ans